package org.example.zookeeper;

import org.example.zookeeper.config.AppProperties;
import org.example.zookeeper.config.DriverType;
import org.example.zookeeper.config.ZkProperties;
import org.example.zookeeper.consumer.ChildrenNodeFetcher;
import org.example.zookeeper.inspect.DubboInspect;
import org.example.zookeeper.inspect.ServiceInfo;
import org.example.zookeeper.test.ZookeeperTesterFactory;
import org.yaml.snakeyaml.Yaml;

import java.io.FileWriter;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

public class ZookeeperApplication {
    public static void main(String[] args) throws Exception {
//        test();
//        child_test();
        dubbo_inspect();
    }

    private static void dubbo_inspect() throws Exception {
        final ZkProperties zkConfig = loadProperties();
        DubboInspect dubboInspect = new DubboInspect();
        List<ServiceInfo> serviceInfos = dubboInspect.inspect(zkConfig);
        System.out.println("++++++++++++++++++++++++");
        FileWriter writer = null;
        try {
            writer = new FileWriter("data3/zk-inspect.csv");
            writer.write(ServiceInfo.header());
            writer.write('\n');
            for (ServiceInfo serviceInfo : serviceInfos) {
                writer.write(serviceInfo.toString());
                writer.write('\n');
            }
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }

    private static void test() {
        final ZkProperties zkConfig = loadProperties();
        ZookeeperTesterFactory.createTester(DriverType.ZK_CLIENT).test(zkConfig);
        ZookeeperTesterFactory.createTester(DriverType.CURATOR).test(zkConfig);
    }

    private static void child_test() throws Exception {
        final ZkProperties zkConfig = loadProperties();
        ChildrenNodeFetcher fetcher = new ChildrenNodeFetcher();
        List<String> result = fetcher.fetchChildren(zkConfig, "/zk-client");
        System.out.println(result);
        Map<String, List<String>> map = fetcher.fetchChildrenDepth2(zkConfig, "/zk-curator");
        System.out.println(map);
    }

    private static ZkProperties loadProperties() {
        InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("application.yml");
        Yaml yaml = new Yaml();
        AppProperties prop = yaml.loadAs(is, AppProperties.class);
        return prop.getZk();
    }
}
